<template>
  <a-modal
    :open="visible"
    title="重置用户密码"
    :keyboard="false"
    :maskClosable="false"
    @cancel="onCancel"
    @ok="onSubmit"
    :confirmLoading="submitLoading"
    :width="500"
  >
    <a-form ref="formRef" :model="formModel" :="formLayout" :rules="rules">
      <a-form-item label="用户名" prop="password">
        <a-input :value="username" disabled></a-input>
      </a-form-item>
      <a-form-item label="新密码" prop="password">
        <a-input v-model:value="formModel.password" type="password"></a-input>
      </a-form-item>
      <a-form-item label="重复密码" prop="password2">
        <a-input v-model:value="formModel.password2" type="password"></a-input>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { RuleObject } from "ant-design-vue/es/form/interface";
import api from "@/api/system/user";
import { FormInstance, message } from "ant-design-vue";
import { ref, reactive } from "vue";
const submitLoading = ref(false);
const props = defineProps({
  visible: { type: Boolean, required: true },
  id: { type: String, required: true },
  username: { type: String, required: true },
});
const emits = defineEmits(["update:visible"]);

/**
 * 表单布局方式
 */
const formLayout = {
  labelCol: { span: 6 },
  labelAlign: "right",
  wrapperCol: { span: 16 },
};

/**
 * 验证规则
 */
const rules: Record<string, Array<RuleObject>> = {
  newPassword: [
    {
      required: true,
      message: "请输入新密码信息",
    },
    {
      min: 6,
      message: "密码长度不能小于6位",
    },
  ],
  newPassword2: [
    {
      required: true,
      validator(rule, value, callback) {
        if (!value) {
          callback("请输入重复密码信息");
        }
        if (value == formModel.password) {
          callback();
        } else {
          callback("两次输入密码不一致，请重新输入");
        }
      },
    },
  ],
};

const formRef = ref<FormInstance>();

const formModel = reactive({ password: "", password2: "" });

const onCancel = () => {
  emits("update:visible", false);
};
const onSubmit = () => {
  formRef.value.validate().then(() => {
    api
      .resetPassword({
        id: props.id,
        password: formModel.password,
      })
      .then(() => {
        message.success("密码修改成功");
        emits("update:visible", false);
      })
      .finally(() => {
        submitLoading.value = false;
      });
    submitLoading.value = true;
  });
};
</script>

<style lang="less" scoped></style>
